function selectedChan_bin = bciChanSelect(epoch, label, nChans)
% selectedChan_bin = bciChanSelect(epoch, label, nChans)
% select channels using r-square meausure 

% <>
doRSqu = true;
selectedChan=[];

if doRSqu,
    classes = unique(label);
    nClasses = length(classes);
    nPairs = (nClasses-1)*nClasses/2;
    subNchan = max(1,floor(nChans/nPairs));
    
    r2 = zeros(size(epoch,1),size(epoch,2),nPairs);
    R2 = zeros(size(epoch,1),nPairs);
    classPair=zeros(nPairs,2);
    
    k=0;
    for k1=1:nClasses-1,
        for k2=k1+1:nClasses,
            k=k+1;
            classPair(k,:) = [k1,k2];
        end
    end
    
    for k=1:nPairs,
        r2(:,:,k) = ecogRsquare(epoch(:,:,label==classes(classPair(k,1))),...
            epoch(:,:,label==classes(classPair(k,2))),3);
        % determine sum of squares
        R2(:,k)=sum(r2(:,:,k).^2,2);
        [R2sorted sortIdx]=sort(R2(:,k),'descend');
        selectedChan=union(selectedChan,sortIdx(1:subNchan));
    end
    chanToAdd = nChans-length(selectedChan);
    if chanToAdd>0,
        unselectedChan = setdiff(1:size(epoch,1),selectedChan);
        [R2sorted sortIdx] = sort(sum(R2(unselectedChan,:),2),'descend');
        selectedChan=union(selectedChan,unselectedChan(sortIdx(1:chanToAdd)));
    end
end

selectedChan_bin=false(1,size(epoch,1));
selectedChan_bin(selectedChan)=true;
